<template>
  <div id="outer-layer">
    <div id="draw-box">
      <div id="canvas-box">
        <div id="toolbox">
          <a title="Pick tool" id=pick-tool><i class="fa fa-location-arrow"></i></a>
          <a title="Insert image" id="insert-image"><i class="fa fa-file-image-o"></i></a>

          <a title="Insert text" id="text-tool"><i class="fa fa-text-width"></i></a>
          <a title="Pencil" id="pencil-tool"><i class="fa fa-pencil"></i></a>

          <a title="Square" id="square-tool"><i class="fa fa-square-o"></i></a>
          <a title="Line" id="line-tool"><i class="fa fa-long-arrow-right"></i></a>

          <!--<a title="Cut" id="cut"><i class="fa fa-cut"></i></a>-->
          <a title="Copy" id="copy"><i class="fa fa-copy"></i></a>
          <a title="Paste" id="paste"><i class="fa fa-paste"></i></a>

          <a title="undo" id="undo"><i class="fa fa-undo"></i></a>
          <a title="redo" id="redo"><i class="fa fa-repeat"></i></a>
        </div>

        <div id="zwibbler" style="border:1px solid #000"></div>
        <div id="progress"></div>
      </div>

      <div id="editGraph">
        <a title="Add shadow" id="shadow"><i class="fa fa-glass" style="text-shadow: 3px 3px 3px #fff"></i></a>

        <a title="Make transparent" id="transparent"><i class="fa fa-glass" style="opacity:0.5"></i></a>

        <!--<a title="  Change font" id=font><i class="fa fa-font"></i></a>-->

        <a title="Inrease font size" id="font-increase"><i class="fa fa-plus"></i></a>

        <a title="Decrease font size" id="font-decrease"><i class="fa fa-minus"></i></a>

        <a title="Text alignment" id="alignment"><i class="fa fa-align-center"></i></a>
      </div>

      <div id="operate-btn">
        <el-button @click="discardChanges()">丢弃修改</el-button>
        <el-button @click="saveChanges()">保存修改</el-button>
        <el-button @click="downloadPng()">下载图片</el-button>
      </div>

      <form style="display:none" method="post"
            enctype="multipart/form-data"
            action="http://zwibbler.com/temp.py">
        <input type="file" name="file" id="fileinput" accept="image/*">
      </form>
    </div>

    <div id="image-box" @click="loadPriorCanvas($event)">
      <!--<img src="../assets/background.jpg"/>-->
    </div>
  </div>
</template>

<script>
  import ElButton from "../../node_modules/element-ui/packages/button/src/button";
  export default {
    components: {ElButton},
    data () {
      return {
        canvas: null,
        canvasObjects: [],
        canvasImages: []
      }
    },
    mounted () {
      this.initCanvas()
    },
    methods: {
      initCanvas () {
        this.canvas = Zwibbler.create("zwibbler", {
          autoPickTool: true,
          showToolbar: false,
          defaultFontSize: 20,
          defaultFont: "Bitter",
          multilineText: true,
          defaultFillStyle: "transparent",
          background: "#fff"
        });

        this.exportDOM();
        this.uploadImage();
      },
      exportDOM () {
        let zwibbler = this.canvas;

        $("#font").hide();
        $("#font-increase").hide();
        $("#font-decrease").hide();
        $("#shadow").hide();
        $("#transparent").hide();
        $("#alignment").hide();

        $("#insert-image").click(function(e) {
          $("#fileinput").click();
        });

        $("#pick-tool").click(function(e) {
          zwibbler.usePickTool();
        });

        $("#text-tool").click(function(e) {
          zwibbler.useTextTool();
        });

        $("#undo").click(function(e) {
          zwibbler.undo();
        });

        $("#redo").click(function(e) {
          zwibbler.redo();
        });

        $("#cut").click(function(e) {
          zwibbler.copy();
          zwibbler.deleteSelection();
        });

        $("#copy").click(function(e) {
          zwibbler.copy();
        });

        $("#paste").click(function(e) {
          zwibbler.paste();
        });

        $("#square-tool").click(function(e) {
          //zwibbler.useSquareTool();
          zwibbler.useRectangleTool({
            fillStyle: "transparent"
          });
        });

        $("#line-tool").click(function(e) {
          zwibbler.useLineTool({
            lineWidth: 3
          });
        });

        $("#pencil-tool").click(function(e) {
          zwibbler.useBrushTool({lineWidth: 3});
        });

        // todo: font
        let Fonts = [
          "微软雅黑",
          "黑体",
          "楷体"
        ];
        let Properties = {};

        // When the selection changes, zwibbler will call this function
        zwibbler.on("selected-nodes", function(e) {
          let ids = zwibbler.getSelectedNodes();

          let types = {};
          Properties = {
            "shadow": false,
            "font": "微软雅黑",
            "fillStyle": "#808080",
            "textAlign": "left",
            "fontSize": 20
          };

          for (let i = 0; i < ids.length; i++ ) {
            let type = zwibbler.getNodeType(ids[i]);
            if (type === "PathNode") {
              types[type] = true;
              if (zwibbler.getNodeProperty(ids[i], "closed")) {
                type = "PathNode-closed";
              } else {
                type = "PathNode-open";
              }
            } else if (type === "TextNode") {
              Properties["fontName"] = zwibbler.getNodeProperty(ids[i],
                "fontName");
            }

            let shadow = zwibbler.getNodeProperty(ids[i], "shadow");
            if (shadow !== undefined) {
              Properties["shadow"] = shadow;
            }

            let fillStyle = zwibbler.getNodeProperty(ids[i], "fillStyle");
            if (fillStyle !== undefined) {
              Properties["fillStyle"] = fillStyle;
            }

            let alignment = zwibbler.getNodeProperty(ids[i], "textAlign");
            if (alignment !== undefined) {
              Properties["textAlign"] = alignment;
            }

            let fontSize = zwibbler.getNodeProperty(ids[i], "fontSize");
            if (fontSize !== undefined) {
              Properties["fontSize"] = fontSize;
            }

            types[type] = true;
          }

          $("#shadow").toggle(ids.length > 0);
          $("#font").toggle(types["TextNode"] === true);
          $("#transparent").toggle(types["PathNode-closed"] === true);
          $("#alignment").toggle(types["TextNode"] === true);
          $("#font-increase").toggle(types["TextNode"] === true);
          $("#font-decrease").toggle(types["TextNode"] === true);
        });

        $("#shadow").on("click", function(e) {
          Properties["shadow"] = !Properties["shadow"];
          zwibbler.setNodeProperty(zwibbler.getSelectedNodes(), "shadow",
            Properties["shadow"]);
        });

        $("#font").on("click", function(e) {
          let i = 0;
          for(; i < Fonts.length; i++ ) {
            if ( Properties["fontName"] === Fonts[i] ) {
              i++; break;
            }
          }
          let newFont = Fonts[i%Fonts.length];
          Properties["fontName"] = newFont;

          zwibbler.setNodeProperty(zwibbler.getSelectedNodes(), "fontName", newFont);
        });

        $("#transparent").on("click", function(e) {
          let colour = Zwibbler.parseColour(Properties["fillStyle"]);
          if (colour.a === 1) {
            colour.a = 0.7;
          } else {
            colour.a = 1;
          }

          Properties["fillStyle"] = Zwibbler.makeColour(colour);

          zwibbler.setNodeProperty(zwibbler.getSelectedNodes(),
            "fillStyle", Properties["fillStyle"]);
        });

        $("#font-increase").click(function(e) {
          Properties["fontSize"] *= 1.1;
          zwibbler.setNodeProperty(zwibbler.getSelectedNodes(),
            "fontSize", Properties["fontSize"]);
        });

        $("#font-decrease").click(function(e) {
          Properties["fontSize"] *= 1/1.1;
          zwibbler.setNodeProperty(zwibbler.getSelectedNodes(),
            "fontSize", Properties["fontSize"]);
        });

        $("#alignment").click(function(e) {
          if (Properties["textAlign"] === "left") {
            Properties["textAlign"] = "centre";
          } else if (Properties["textAlign"] === "centre") {
            Properties["textAlign"] = "right";
          } else {
            Properties["textAlign"] = "left";
          }

          zwibbler.setNodeProperty(zwibbler.getSelectedNodes(), "textAlign",
            Properties["textAlign"]);
        });
      },
      uploadImage () {
        let zwibbler = this.canvas;

        $("#fileinput").on("change", function(e) {
          let form = this.parentNode;
          upload(form);
          form.reset();
        });

        function upload( form ) {
          let progress = new ProgressNotification("Reading file");
          let xhr = new XMLHttpRequest();
          let fd = new FormData(form);

          xhr.upload.addEventListener("progress",
            function( e ) {
              progress.update( e.loaded / e.total );
            }, false
          );

          xhr.addEventListener("load",
            function( e ) {
              progress.done();
              uploadDone( "ok", $.parseJSON( xhr.response ));
            }, false
          );

          xhr.addEventListener("error",
            function( e ) {
              progress.error("Error");
              uploadDone( "error", null);
            }, false
          );

          xhr.addEventListener("abort",
            function( e ) {
              progress.error("Aborted");
              uploadDone( "aborted", null);
            }, false
          );
          xhr.open(form.method, form.action);
          xhr.send(fd);
        }

        function uploadDone(status, result) {
          if (status === "ok") {
            // todo：CHANGE THIS CODE TO PROCESS YOUR OWN RESPONSE
            let url = "http://zwibbler.com/temp.py?fileid=" + result.fileid;

            zwibbler.beginTransaction();
            let nodeId = zwibbler.createNode("ImageNode", {
              url: url
            });
            zwibbler.translateNode(nodeId, 100, 100);
            zwibbler.commitTransaction();
          }
        }

        // Display multiple upload progress notifications
        function ProgressNotification(name) {
          this.name = name;
          ProgressNotification.all.push(this);
          this.div = $("<div>");
          $("#progress").append(this.div).show();
          this.update(0);
        }
        ProgressNotification.all = [];
        ProgressNotification.prototype = {
          update: function(percent) {
            this.div.text(this.name + "... " + Math.round(percent * 100) +
              "%");
          },
          error: function(message) {
            let self = this;
            let input = $("<input>").
            attr("type", "button").
            val("OK");

            input.click(function(e) {
              self.done();
            });

            this.div.html(this.name + "... " +  message);
            this.div.append(input);
          },
          done: function() {
            this.div.remove();
            let all = ProgressNotification.all;
            for(let i = 0; i < all.length; i++) {
              if (all[i] === this) {
                all.splice(i, 1);
                break;
              }
            }

            if (all.length === 0) {
              $("#progress").hide();
            }
          }
        };
      },
      discardChanges () {
        this.canvas.newDocument();
      },
      downloadPng () {
        this.canvas.download("png", "zwibbler.png");
      },
      saveChanges () {
        let imgUrl = this.canvas.save("png");
       
        $("#image-box").append(`<img src='${imgUrl}' />`);

        this.canvasImages.push(imgUrl);
        this.canvasObjects.push(this.canvas.save("zwibblerfff"));
        console.log("save++++++++++++++++++++++++++")
        console.log(this.canvas.save("zwibblerffff"))

        this.discardChanges()
      },
      loadPriorCanvas (event) {
        let dataSrc = event.target.src;
        let dataIdx = -1;
        this.canvasImages.forEach((data, index) => {
          if (data === dataSrc) {
            dataIdx = index
          }
        });
        if (dataIdx !== -1) {
          this.canvas.load("zwibblerfff", this.canvasObjects[dataIdx])
        }
      }
    }
  }
</script>

<style>
  #outer-layer {
    background: #000000;
    width: 100%;
    height: 100%;
    padding-top: 50px;
    position: fixed;
    overflow: scroll;
  }
  #draw-box {
    width: 970px;
    margin: 0 auto;
    zoom: 1;
    overflow: hidden;
  }

  #toolbox {
    width: 160px;
    padding: 5px;
    border-radius: 15px;
    background: rgba(255, 255, 255, 0.8);
    float: left;
  }
  #toolbox a {
    margin: 8px;
    width: 50px;
    height: 50px;
    border-radius: 5px;
    display: inline-block;
    text-align: center;
    cursor: pointer;
  }
  #toolbox a:hover {
    background-color: #999
  }
  #toolbox i {
    margin-top: 5px;
    font-size: 40px;
    color: #727272;
  }

  /*todo:*/
  .select-tool {
    background-color: #999
  }

  #zwibbler {
    width: 698px;
    height: 338px;
    /*border-radius: 15px;*/
    /*background: url("../assets/background.jpg") right;*/
    float: left;
    margin-left: 100px;
  }

  #editGraph {
    width: 308px;
    height: 36px;
    padding: 5px;
    margin-top: 30px;
    margin-left: 270px;
    border-radius: 5px;
    float: left;
    background: rgba(255, 255, 255, 0.8);
  }
  #editGraph a {
    margin: 8px;
    width: 30px;
    display: inline-block;
    text-align: center;
    cursor: pointer;
  }
  #editGraph a:hover {
    background-color: #999
  }

  #operate-btn {
    float: right;
    margin-top: 46px;
  }
  #operate-btn button{
    width: 100px;
    height: 30px;
    background: rgba(255, 255, 255, 0.8);
    color: #333;
    font-size: 15px;
    line-height: 9px;
  }

  #image-box {
    width: 970px;
    margin: 50px auto;
    zoom: 1;
    overflow: hidden;
  }
  #image-box img {
    height: 150px;
    float: left;
    margin-right: 10px;
    margin-bottom: 10px;
  }

  #progress {
    display: none;
    position: absolute;
    top: 0;
    right: 200px;
    box-shadow: 3px 3px 3px #444;
    background: #ccc;
    color: black;
    border-bottom-left-radius: 4px;
    font-family: arial, sans;
  }

  #progress div {
    border-top: 1px solid #888;
    padding: 5px;
  }

</style>
